package com.wanxi.service.impl;

import com.wanxi.dao.ProductDao;
import com.wanxi.dao.impl.ProductDaoImpl;
import com.wanxi.dto.ProductDto;
import com.wanxi.model.ProductModel;
import com.wanxi.service.ProductService;
import com.wanxi.util.Tool;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;

public class ProductServiceImpl implements ProductService {
    private ProductDao productDao = new ProductDaoImpl();

    @Override
    public String add(ProductModel productModel) {
        return Tool.getResult(productDao.add(productModel));
    }

    @Override
    public String update(ProductModel productModel) {
        return Tool.getResult(productDao.update(productModel),"imgHrefs","names","contents");
    }

    @Override
    public String delete(ProductModel productModel) {
        return Tool.getResult(productDao.delete(productModel));
    }

    @Override
    public ProductDto findById(ProductModel productModel) {
        return productDao.findById(productModel);
    }

    @Override
    public List<ProductDto> findAll(ProductModel productModel) {
        return productDao.findAll(productModel);
    }

    @Override
    public List<ProductDto> findAllFront(ProductModel productModel) {
        /**
         * 1.判断redis里面是否有数据
         * 2.如果有，则取redis
         * 3.没有，则取数据库，然后存入redis
         */
        List<ProductDto> list = new ArrayList<>();
        Jedis jedis = new Jedis();
        boolean aa = jedis.exists("imgHrefs");
        if (aa) {
            List<String> imgHrefs = jedis.lrange("imgHrefs", 0, jedis.llen("imgHrefs"));
            List<String> names = jedis.lrange("names", 0, -1);
            List<String> contents = jedis.lrange("contents", 0,-1);
            for (int i = 0; i < imgHrefs.size(); i++) {
                list.add(ProductDto.builder()
                        .imgHref(imgHrefs.get(i))
                        .name(names.get(i))
                        .content(contents.get(i))
                        .build());
            }
        } else {
            list = productDao.findAll(productModel);
            for (int i = 0; i < list.size(); i++) {
                jedis.rpush("imgHrefs", list.get(i).getImgHref());
                jedis.rpush("names", list.get(i).getName());
                jedis.rpush("contents", list.get(i).getContent());
            }
        }
        return list;
    }

    @Override
    public int count(ProductModel productModel) {
        return productDao.count(productModel);
    }
}
